package com.iot.inclinometer.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.iot.inclinometer.R;
import com.iot.inclinometer.dao.IBaseInfoDao;
import com.iot.inclinometer.dao.ICorrectDataInfoDao;
import com.iot.inclinometer.dao.IDataInfoDao;
import com.iot.inclinometer.dao.ILeijiInfoDao;
import com.iot.inclinometer.dao.IObserveInfoDao;
import com.iot.inclinometer.dao.IRealInfoDao;
import com.iot.inclinometer.dao.impl.BaseInfoDaoImpl;
import com.iot.inclinometer.dao.impl.CorrectDataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.DataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.LeijiInfoDaoImpl;
import com.iot.inclinometer.dao.impl.ObserveInfoDaoImpl;
import com.iot.inclinometer.dao.impl.RealInfoDaoImpl;
import com.iot.inclinometer.pojo.CorrectDataInfo;
import com.iot.inclinometer.pojo.DataInfo;
import com.iot.inclinometer.pojo.LeijiInfo;
import com.iot.inclinometer.pojo.ObserveInfo;
import com.iot.inclinometer.pojo.RealInfo;
import com.iot.inclinometer.util.BaseUtil;
import com.iot.inclinometer.util.Common;
import com.iot.inclinometer.util.ContextApplication;
import com.iot.inclinometer.util.InclinometerControl;
import com.iot.inclinometer.util.MeanMethod;
import com.iot.inclinometer.util.TableAdapter;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 监测数据界面*  
 */
public class r_MeasureDataUI extends Activity /*implements View.OnTouchListener*/ {
	private TextView titleView;		//显示标题(产品型号)
	
	private String model=null;    //产品型号
	private  Boolean ifSecond=false;
	/**
	 * 表格列深度
	 */
	private double[] depthArray = new double[1];
	/**
	 * 表格列偏移
	 */
	private double[] thetaXArray = new double[1];//thetaXOZ
	private double[] thetaYArray = new double[1];//thetaYOZ
	private double[] RthetaXArray = new double[1];//thetaXOZ
	private double[] RthetaYArray = new double[1];//thetaYOZ
	private double[] lthetaXArray = new double[1];//thetaXOZ
	private double[] lthetaYArray = new double[1];//thetaYOZ
	private double[] llthetaXArray = new double[1];//thetaXOZ
	private double[] llthetaYArray = new double[1];//thetaYOZ
	private double[] TcorrectArray = new double[1];
	private double[] thetaArray = new double[1];

	private static double[] XArray;//存放获取的n组数据
	private static double[] YArray;
	private static double[] ZArray;
	private static double[] TArray;
	
	private ListView tableListView;
	private ImageView newProBtn;
	private ImageView oldProBtn;
	private ImageView paintBtn;
	private ImageView uploadDBBtn;
	private ImageView outputBtn;
	private ImageView exitBtn;
	private LinearLayout chatLoc;

	// 初始化输入控件
	private EditText observerEdit;
	private EditText date_edit;
	//时间选择器
	private TimePickerView pvTime;
	private Spinner intervalSpinner;
	private Spinner measureangleSpinner;
	private Spinner qjSpinner;
	
	/** 保存观测信息按钮 */
	private Button saveObserveInfoBtn;
	/** 保存测量信息按钮 */
	private Button saveMeasureInfoBtn;
	/** 测量按钮 */
	private Button measureBtn;
	/** 确定按钮 */
	private Button sureBtn;
	/** 回退按钮，删除上次测量 */
	private Button backBtn;
	/** 显示系统测试是否稳定*/
	private TextView systemTestView;
	/** 显示theta*/
	private TextView thetaView;

	// 初始化显示的TextView
	private TextView itemNameView;
	private TextView drillTextView;
	private TextView intervalTextView;
	private TextView measureangleTextView;
	//private TextView readNumTextView;
	private TextView temperatureTextView;
	private TextView measurecountTextView;
	private EditText second_edit;
	/** 传入的孔深 */
	private double depth;
	/** 传入的基本信息ID */
	private int baseId;
	/** 传入的工点名称*/
	private String itemName;
	/** 传入的钻孔编号 */
	private String drillNum;
	/** 表示由哪个界面进入的监测界面 */
	private String from;
	/** 表示本次测量属于哪个观测信息ID */
	private int obId;
	/** 表示当前测量深度点的位置 */
	private int currentMeasureTag = 0;
	/** 表示当前数组长度，有多少个需要测量的深度点 */
	private int length = 0;
	/** 坐标图X轴数据 */
	private double[] depthX = null;
	/** 坐标图Y轴数据 */
	private double[] lxerrorY = null;
	private double[] lyerrorY = null;
	/** 保存测量次数，如果测量了2次，那么所有按钮失效 */
	private int meaCount = 1;
	/** 保存观测的次数，为observeInfo中的count赋值*/
	private int observecount=1;
	private int _obId2;
	private String meaAngleNO1;//用来记录第一次测量的测试方向（正反两次观测为一次完整观测）
	private final String MEASURE_ANGLE_0="A0方向";
	private final String MEASURE_ANGLE_180="A180方向";
	
	private String IP=null;
	private int Port=0;
	private int readNum=50;//每次测量读数组数
	private int temperature=0;
	
	private InputMethodManager inputMethodManager;       //控制键盘隐藏
	
	private int lightGreen=Color.parseColor("#98FB98");
	private int lightRed=Color.parseColor("#FF3333");

	private IBaseInfoDao baseInfoDao=new BaseInfoDaoImpl(this);
	private IObserveInfoDao observeInfoDao = new ObserveInfoDaoImpl(this);
	private IDataInfoDao dataInfoDao = new DataInfoDaoImpl(this);
	private ICorrectDataInfoDao correctDataInfoDao=new CorrectDataInfoDaoImpl(this);
	private ILeijiInfoDao leijiInfoDao=new LeijiInfoDaoImpl(this);
	private IRealInfoDao realInfoDao=new RealInfoDaoImpl(this);
	
	
	private int w=-100;
	private byte[] bytefh=new byte[4];
	private byte[] bytes=new byte[16];
	private int[] t=new int[16];
	private int[] temp=new int[16];
	private double  variance=50000;
	private double  second=0.5;
	
	private SoundPool sp;//声明一个SoundPool   
	private int music;//定义一个整型用load（）；来设置suondID  
	private ProgressDialog progressDialog; 
	private MyAsyncTask task;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE); // 取消标题
		super.onCreate(savedInstanceState);
		
	    // -----------初始化参数start-------------
	    
		Intent intent = getIntent();
		try {
			depth =Double.parseDouble((intent.getStringExtra("depth")));
		} catch (Exception e) {
			Log.i("info", "传入的深度为NULL，不能进行数字转换。");
			depth = 20; // 数据库没数据的时候也可以显示
		}
		itemName= intent.getStringExtra("itemName");
		baseId = intent.getIntExtra("baseId", 0);
		drillNum = intent.getStringExtra("drillNum");
		from = intent.getStringExtra("from");
		// -------------end--------------
		if ("new".equals(from)) {
			setContentView(R.layout.r_measure_data_activity);
		}
		if ("old".equals(from)) {
			setContentView(R.layout.r_measure_data_activity_from_oldproject);
			
		}
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		SharedPreferences sharedPreferences=ContextApplication.getAppContext().getSharedPreferences("configuration",0);
		model=sharedPreferences.getString("Model","");
		readNum=sharedPreferences.getInt("ReadNum",0);
		variance=Double.valueOf(sharedPreferences.getString("variance",null));
		initView();
		initMeasureView(depth);//初始化绘图界面
		setBtnListener();
		initListView(0);//初始化表格界面
		sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数，第二数据流类型，第三为声音质量   
		music = sp.load(getApplicationContext(), R.raw.collide, 1); //把你的声音素材放到res/raw里，第2个参数即为资源文件，第3个为音乐的优先级   
		progressDialog=new ProgressDialog(r_MeasureDataUI.this); //获取测量数据进度对话框
		progressDialog.setTitle("提示信息");
		progressDialog.setMessage("正在获取数据，请稍后......");
		 //    设置setCancelable(true); 表示我们能取消这个弹出框;等下载完成之后再让弹出框消失
		progressDialog.setCancelable(true);
		 //    设置ProgressDialog样式为圆圈的形式
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		
	}
	    
	// 更新图表
	//chatLoc.removeAllViews();
	//initMeasureView(depth, depthX, lxerrorY, lyerrorY);
	// 更新表格
	//initGridView();
	/**
	 * 初始化控件,(部分是公共的)
	 */
	private void initView() {
		titleView=(TextView) findViewById(R.id.tv_top_title); 	//初始化标题
		titleView.setText(titleView.getText() + (Common.isEmpty(model) ? "" : "(" + model + ")"));
		// 初始化输入控件
				observerEdit = (EditText) findViewById(R.id.observer_edit);
				date_edit = (EditText) findViewById(R.id.time_edit);
				intervalSpinner = (Spinner) findViewById(R.id.interval_spinner);
				measureangleSpinner = (Spinner) findViewById(R.id.measureangle_spinner);
				qjSpinner = (Spinner) findViewById(R.id.qj_spinner);
				saveObserveInfoBtn = (Button) findViewById(R.id.observe_save_btn);
				saveObserveInfoBtn.setEnabled(true);
				saveMeasureInfoBtn = (Button) findViewById(R.id.all_save_btn);
				saveMeasureInfoBtn.setEnabled(false); // 保存测量数据按钮
				saveMeasureInfoBtn.setBackgroundColor(lightRed);
				measureBtn = (Button) findViewById(R.id.measure_btn);
				measureBtn.setEnabled(false);  // 测量按钮
				measureBtn.setBackgroundColor(lightRed);
				sureBtn = (Button) findViewById(R.id.sure_btn);
				sureBtn.setEnabled(false);  // 测量按钮
				sureBtn.setBackgroundColor(lightRed);
				backBtn = (Button)findViewById(R.id.back_btn);
				backBtn.setEnabled(false);
				backBtn.setBackgroundColor(lightRed);

				systemTestView = (TextView) findViewById(R.id.sys_test_result_view);
				thetaView=(TextView) findViewById(R.id.theta_view);
				
				itemNameView = (TextView) findViewById(R.id.item_name_view);
				drillTextView = (TextView) findViewById(R.id.drill_num_view);
				intervalTextView = (TextView) findViewById(R.id.interval_view);
				measureangleTextView = (TextView) findViewById(R.id.measureangle_view);
				//readNumTextView = (TextView) findViewById(R.id.read_num_view);
				temperatureTextView=(TextView) findViewById(R.id.temperature_view);
				measurecountTextView = (TextView) findViewById(R.id.measurecount_view);
				second_edit = (EditText) findViewById(R.id.second_edit);
				itemNameView.setText(itemName);
				drillTextView.setText(drillNum);
				//readNumTextView.setText(readNum+"");//每次测量读数组数
				temperatureTextView.setText(temperature+"");
		
		if ("new".equals(from)) {
			oldProBtn = (ImageView) findViewById(R.id.old_pro_btn);
		}
		if ("old".equals(from)) {
			newProBtn = (ImageView) findViewById(R.id.new_pro_btn);
			/***判断上次的观测信息是否有对应的修正数据***/
			String measureangle1 = measureangleSpinner.getSelectedItem().toString();// 当前进行测量的方向是这个	
			List<ObserveInfo> alls1= new ArrayList<ObserveInfo>();
			alls1= observeInfoDao.selectObserverInfos(baseId,
					measureangle1);
			if (alls1.size() < 1) {                                 
				measurecountTextView.setText("1");
			} else {
			int max1= 1;
			for (ObserveInfo observeInfo3 : alls1) {
				int i = observeInfo3.getCount();
				if (i > max1){//得到最大的观测次数count的值，即最近的一次观测
					max1= i;
				}
			 }
			ObserveInfo observeInfo1=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseId,max1);//在ObserveInfo表里找到最近的count值
			int obId=observeInfo1.getObserveId();//count值对应的ob_id
			int obId1=obId+1;
			List<CorrectDataInfo> correctDataInfos=correctDataInfoDao.selectDataInfos(obId);//根据ob-id从correctDataInfo表里查找对应的数据
			if (correctDataInfos.size()<=0) {//修正表里面没有上次的修正数据则删除上次对应的观测信息和实测信息
				observeInfoDao.deleteObserveInfoByobId(obId);//0度
				observeInfoDao.deleteObserveInfoByobId(obId1);//180度
				dataInfoDao.deleteDataInfosByobId(obId);//0度
				dataInfoDao.deleteDataInfosByobId(obId1);//180度
				leijiInfoDao.deleteLeijiInfosByobId(obId);
				realInfoDao.deleteRealInfosByobId(obId);
				realInfoDao.deleteRealInfosByobId(obId1);
				}else{		
				}
	     }		
		}
		paintBtn = (ImageView) findViewById(R.id.paint_btn);
		outputBtn = (ImageView) findViewById(R.id.output_btn);
		uploadDBBtn =  (ImageView) findViewById(R.id.uploaddbToServer_btn);
		exitBtn = (ImageView) findViewById(R.id.exit_btn);
		chatLoc = (LinearLayout) findViewById(R.id.chatLocation);
		tableListView = (ListView) findViewById(R.id.table_list);
		int lastCount=observeInfoDao.getLastCountByBaseId(baseId);//上一次测量的测试cishu
		String lcount=String.valueOf(lastCount);
		if(lcount==null||lcount=="")
		{
			measurecountTextView.setText("1");
		}else{
			measurecountTextView.setText(lastCount+1+"");
		}
		String lastObserver=observeInfoDao.getLastObserverByBaseId(baseId);//上一次测量的测试人
		observerEdit.setText(lastObserver);
		String lastInterval=observeInfoDao.getLastIntervalByBaseId(baseId);//上一次测量的测试jiange
		if(lastInterval==null||lastInterval=="")
		{	
		}else{
			setSpinnerItemSelectedByValue(intervalSpinner,lastInterval);
			initArrays();
		}

		//时间选择器
		pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
			@Override
			public void onTimeSelect(Date date, View v) {
				((EditText)v).setText(Common.getTime(date,null));
			}
		})
				.setType(new boolean[]{true, true, true, true, true, true})
				.setLabel("年", "月", "日", "时", "分", "秒")
				.setCancelText("取消")
				.setSubmitText("确定")
				.build();
	}
	public void setSpinnerItemSelectedByValue(Spinner spinner,String value){
	    SpinnerAdapter apsAdapter= spinner.getAdapter(); //得到SpinnerAdapter对象
	    int k= apsAdapter.getCount();
	    for(int i=0;i<k;i++){
	        if(value.equals(apsAdapter.getItem(i).toString())){
	            spinner.setSelection(i,true);// 默认选中项
	            break;
	        }
	    }
	} 
	public void initListView(int isBack) {
		// 创建一个List对象，List对象的元素是Map
		List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
		setListItems(listItems,0,isBack);
		TableAdapter tableAdapter = new TableAdapter(listItems, this,currentMeasureTag);
		tableListView.setAdapter(tableAdapter);		
		if (currentMeasureTag>=13) {
			tableListView.setSelection(currentMeasureTag-12);
			tableAdapter.notifyDataSetInvalidated();
			//notifyDataSetInvalidated()会刷新数据并置顶ListView,  notifyDataSetChanged()测只是刷新数据不置顶
		}	
	}

	/**
	 * 根据钻孔深度初始化界面
	 * 
	 * @param _depth
	 *            钻孔深度
	 */
	private void initMeasureView(double _depth) {

		String[] titles = new String[] { "偏移线", "中轴" };

		List<double[]> x = new ArrayList<double[]>();
		List<double[]> y = new ArrayList<double[]>();

		x.add(new double[] { 0, 0 });
		x.add(new double[] { 0, _depth });

		y.add(new double[] { 0, 0 });
		y.add(new double[] { 0, 0 });

		XYMultipleSeriesDataset dataset = buildDataset(titles, x, y);

		int[] colors = new int[] { Color.BLUE, Color.RED };
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE,
				PointStyle.DIAMOND };
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles, true);

		setChartSettings(renderer, null, "深度(米)", "位移（毫米）", 0, _depth, -5, 5,
				Color.RED, Color.BLUE);

		View chart = ChartFactory.getLineChartView(this, dataset, renderer); // 折线图
		chart.setRotation(90.0f);
		chatLoc.addView(chart);
	}


	/**
	 * 动态初始化坐标系图
	 * @param _depth
	 * @param depthX
	 * @param lxerrorY
	 * @param lyerrorY
	 */
	private void initMeasureView(double _depth, double[] depthX, double[] lxerrorY,double[] lyerrorY) {

		String[] titles = new String[] { "A方向偏移线","B方向偏移线", "中轴" };

		List<double[]> x = new ArrayList<double[]>();
		List<double[]> y = new ArrayList<double[]>();
		
		x.add(depthX);
		x.add(depthX);
		x.add(new double[] { 0, _depth });

		y.add(lxerrorY);
		y.add(lyerrorY);
		y.add(new double[] { 0, 0 });

		XYMultipleSeriesDataset dataset = buildDataset(titles, x, y);

		int[] colors = new int[] { Color.BLUE,Color.YELLOW, Color.RED };
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE,PointStyle.CIRCLE,
				PointStyle.DIAMOND };
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles, true);

		setChartSettings(renderer, null, "深度(米)", "位移（毫米）", 0, _depth, -5,5,
				Color.RED, Color.BLUE);

		View chart = ChartFactory.getLineChartView(this, dataset, renderer); // 折线图
		chart.setRotation(90.0f);
		chatLoc.addView(chart); 
	}

	/** * 设置监听，（部分是公共的）*/
	private void setBtnListener() {
		if ("new".equals(from)) {
		oldProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(r_MeasureDataUI.this);
				builder.setMessage("确定退出本次监测吗？");
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent intent = new Intent(r_MeasureDataUI.this, OldProUI.class);
								startActivity(intent);
								sp.release();//释放SoundPool中的所有音频资源
								r_MeasureDataUI.this.finish();
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
				
			}
		});
		}
		if ("old".equals(from)) {
		newProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(r_MeasureDataUI.this);
				builder.setMessage("确定退出本次监测吗？");
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent intent = new Intent(r_MeasureDataUI.this, NewProUI.class);
								startActivity(intent);
								sp.release();//释放SoundPool中的所有音频资源
							
								r_MeasureDataUI.this.finish();
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();				
			}
		});
		}
		paintBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(r_MeasureDataUI.this);
				builder.setMessage("确定退出本次监测吗？");
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent intent = new Intent(r_MeasureDataUI.this, PaintProUI.class);
								startActivity(intent);
								sp.release();//释放SoundPool中的所有音频资源
								r_MeasureDataUI.this.finish();
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();						
			}
		});
		uploadDBBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(r_MeasureDataUI.this);
				builder.setMessage("确定退出本次监测吗？");
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent intent = new Intent(r_MeasureDataUI.this, UploadDBToServerUI.class);
								startActivity(intent);
								sp.release();//释放SoundPool中的所有音频资源
								r_MeasureDataUI.this.finish();
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();
			}
		});

		outputBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new Builder(r_MeasureDataUI.this);
				builder.setMessage("确定退出本次监测吗？");
				builder.setTitle("提示");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent intent = new Intent(r_MeasureDataUI.this,OutputProUI.class);
								startActivity(intent);
								sp.release();//释放SoundPool中的所有音频资源
								r_MeasureDataUI.this.finish();
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
				builder.create().show();	
			}
		});
		exitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sureDialog();
			}
		});
		
		
		
		intervalSpinner.setOnItemSelectedListener(intervalItemSelectedListener);

		// gisboss 优化时间选择
//		date_edit.setOnTouchListener(this);
		date_edit.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					pvTime.show(v);
				}
				return true;
			}
		});

		saveObserveInfoBtn.setOnClickListener(saveObserveInfoListener);
		measureangleSpinner.setOnItemSelectedListener(measureangleItemSelectedListener);
		qjSpinner.setOnItemSelectedListener(qjItemSelectedListener);

		measureBtn.setOnClickListener(measureBtnClickListener); // 测量按钮
		sureBtn.setOnClickListener(sureBtnClickListener); // 测量按钮
		saveMeasureInfoBtn.setOnClickListener(saveDataOnClickListener); // 保存全部测量数据

	
		backBtn.setOnClickListener(backOnClickListener);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	/**
	 * 初始化表中的数据
	 * 
	 * @param listItems
	 *            保存数据键值对的集合
	 * @param count
	 */
	public void setListItems(List<Map<String, Object>> listItems, int count,int isBack) {
		for (int i = 0; i < depthArray.length; i++) {
			Map<String, Object> listItemno = new HashMap<String, Object>();
			listItemno.put("depth", depthArray[i]);
			//判断是否因为回退刷新列表
			if(isBack==1){
				//由于回退，刷新列表，currentMeasureTag为当前回退的位置，
				//在回退的点击事件中已经变为了0，不应该再减去第一次有效测量的结果
				if(i<currentMeasureTag){
					//表格刷新显示之前，已测量深度段的位移要减去第一次有效测量的结果
					listItemno.put("error",Common.remainFourNum(llthetaXArray[i]));
				}else{
					listItemno.put("error",Common.remainFourNum(llthetaXArray[i]));
				}
			}else{
				if(i<=currentMeasureTag){
					//表格刷新显示之前，已测量深度段的位移要减去第一次有效测量的结果
					listItemno.put("error", Common.remainFourNum(llthetaXArray[i]));
				}else{
					listItemno.put("error",Common.remainFourNum(llthetaXArray[i]));
				}                      
			}
			//listItemno.put("error", lxArray[i]);
			listItems.add(listItemno);
		}
	}
	/**
	 * 将测量数据保存到dataInfo表
	 */
	private OnClickListener saveDataOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			List<DataInfo> allDataInfos = new ArrayList<DataInfo>();
			for (int i = 0; i < depthArray.length; i++) {
				DataInfo dataInfo = new DataInfo();
				dataInfo.setDepth(Double.toString(depthArray[i]));
				dataInfo.setThetaX(Double.toString(thetaXArray[i]));//单位：弧度
				dataInfo.setThetaY(Double.toString(thetaYArray[i]));
				dataInfo.setObserverId(obId);
				allDataInfos.add(dataInfo);
			}
			Log.i("info","添加入datatifo，obid为"+obId+",方向"+meaCount);
			Boolean flag = dataInfoDao.insertAll(allDataInfos);
			if (flag == true) { // 表示保存成功
				if (meaCount == 1) { //表示当前对于该孔只测了一个方向角
					saveMeasureInfoBtn.setEnabled(false);
					saveMeasureInfoBtn.setBackgroundColor(lightRed);
					backBtn.setEnabled(false);
					backBtn.setBackgroundColor(lightRed);
					measureangleSpinner.setEnabled(true);
					initMeasureContext();
					// 更新图表
					chatLoc.removeAllViews();
					initMeasureView(depth);
					//更新表格
					int isBack=1;
					initListView(isBack);  //currentMeasureTag已变为0，此处为了让第一个值为0，按“返回”的情况，刷新列表					
					showMsg("请选择其他测试方向！");
					meaCount++;
				} else {
					// 当第二次就会失效了
					saveMeasureInfoBtn.setEnabled(false);
					saveMeasureInfoBtn.setBackgroundColor(lightRed);
					measureangleSpinner.setEnabled(false);
					backBtn.setEnabled(false);
					backBtn.setBackgroundColor(lightRed);
					correctAndSavedata();//修正并保存修正数据
					showMsg("测量完成！");
					}			

			} else {
				showMsg("保存失败，请重新保存！");
			}
			Log.i("info", Boolean.toString(flag));

		}
	};
	
	/**
	 * 修正数据并保存到correct_data_info表
	 */
	private void correctAndSavedata(){
		int obId0;
		int obId180;
		//判断一下当前obId是A0方向的，还是A180方向的（当前obId是第二次测量的）
		if(meaAngleNO1.equals(MEASURE_ANGLE_0)){
			obId0=obId;
			obId180=obId-1;
		}else{
			obId0=obId-1;
			obId180=obId;
		}
		Log.i("info","obId0为"+obId0+",obId180为"+obId180);
		//取刚刚存入数据库的观测结果
		List<DataInfo> DataInfoList0=dataInfoDao.selectDataInfos(obId0);//存放A0方向测量结果
		List<DataInfo> DataInfoList180=dataInfoDao.selectDataInfos(obId180);//存放A180方向测量结果
		int n=DataInfoList0.size();//获得数据的长度
		double[] thetaX0 = new double[n];
		double[] thetaY0 = new double[n];
		double[] thetaX180 = new double[n];
		double[] thetaY180 = new double[n];
		//获得测量的数据，四个角度数组
		for(int i=0;i<n;i++){
			DataInfo item0=DataInfoList0.get(i);
			DataInfo item180=DataInfoList180.get(i);
			thetaX0[i]=Double.parseDouble(item0.getThetaX());//单位：弧度
			thetaY0[i]=Double.parseDouble(item0.getThetaY());
			thetaX180[i]=Double.parseDouble(item180.getThetaX());
			thetaY180[i]=Double.parseDouble(item180.getThetaY());
		}
		int interval = Integer.parseInt(intervalSpinner.getSelectedItem().toString());           	
		Map<String,double[]> result=new HashMap<String, double[]>();
		Log.i("info","thetaX0为"+thetaX0[0]+",thetaY0为"+thetaY0[0]);
		//计算得到修正结果，修正结果中的位移是累计的
		result=InclinometerControl.leijiData(thetaX0,thetaY0,thetaX180,thetaY180,interval);
		double[] leijilx=result.get("lx");//累计位移,单位：cm
		double[] leijily=result.get("ly");
		double[] leijithetaX=result.get("thetaX");
		double[] leijithetaY=result.get("thetaY");
		double[] lx=new double[leijilx.length];//滑动位移
		double[] ly=new double[leijilx.length];
		double[] thetaX=new double[leijilx.length];
		double[] thetaY=new double[leijilx.length];
		double[] zong=new double[leijilx.length];
		List<LeijiInfo> allDataInfos = new ArrayList<LeijiInfo>();//
		for (int i = 0; i < depthArray.length; i++) {
			LeijiInfo leijiInfo = new LeijiInfo();
			leijiInfo.setDepth(Double.toString(depthArray[i]));
			leijiInfo.setLx(Double.toString(leijilx[i]));//单位：弧度
			leijiInfo.setLy(Double.toString(leijily[i]));
			leijiInfo.setThetaX(Double.toString(leijithetaX[i]));//单位：弧度
			leijiInfo.setThetaY(Double.toString(leijithetaY[i]));
			leijiInfo.setObserverId(obId0);
			allDataInfos.add(leijiInfo);
		}
		leijiInfoDao.insertAll(allDataInfos);	
		Log.i("info","添加入leijiinfo,obid为"+obId0);
		if(observecount==1){//第一次观测
			for(int i=0;i<n;i++){
				lx[i]=0;//存的时候，第一次有效观测的值是不能为0(因为以后计算要用)，
				ly[i]=0;//必须保存实际值，在显示、导出时再设置为0
				zong[i]=0;//总位移为两个分位移的平方和再开方
			}
			Log.i("info","第一次观测");
		}else {
			ObserveInfo observeInfo0=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseId,observecount-1);
			int ob_id=observeInfo0.getObserveId();//A0方向的ob_id
			List<LeijiInfo> LeijiInfoList=leijiInfoDao.selectLeijiDataInfos(ob_id);//存放A0方向测量结果
			int n2=LeijiInfoList.size();//获得数据的长度
			double[] lastleiLx = new double[n2];
			double[] lastleiLy = new double[n2];
			double[] lastleiThetaX = new double[n2];
			double[] lastleiThetaY = new double[n2];
			//获得测量的数据，四个角度数组
			for(int i=0;i<n;i++){
				LeijiInfo item=LeijiInfoList.get(i);
				lastleiLx[i]=Double.parseDouble(item.getLx());//单位：cm
				lastleiLy[i]=Double.parseDouble(item.getLy());
				lastleiThetaX[i]=Double.parseDouble(item.getThetaX());
				lastleiThetaY[i]=Double.parseDouble(item.getThetaY());
			}
			List<CorrectDataInfo> correctInfoList=correctDataInfoDao.selectDataInfos(ob_id);//存放A0方向测量结果
			int n3=correctInfoList.size();//获得数据的长度
			double[] lastLx = new double[n3];
			double[] lastLy = new double[n3];
			double[] lastThetaX = new double[n3];
			double[] lastThetaY = new double[n3];
			//获得测量的数据，四个角度数组
			for(int i=0;i<n;i++){
				CorrectDataInfo item=correctInfoList.get(i);
				lastLx[i]=Double.parseDouble(item.getLx());//单位：cm
				lastLy[i]=Double.parseDouble(item.getLy());
				lastThetaX[i]=Double.parseDouble(item.getThetaX());
				lastThetaY[i]=Double.parseDouble(item.getThetaY());
			}
			for(int i=0;i<n;i++){
		    	if(i==0){
		    		lx[i] = (leijilx[i]-lastleiLx[i])*1000+lastLx[i];  //为第一深度时，（本次滑动位移-上一次测量的滑动位移）
		    		ly[i] = (leijily[i]-lastleiLy[i])*1000+lastLy[i];
		    		zong[i]=(double) Math.sqrt(lx[i]*lx[i]+ly[i]*ly[i]);
		    	}else{
		    		lx[i] = (leijilx[i]-lastleiLx[i])*1000+lastLx[i];//（本次滑动位移-上一次测量的滑动位移）+上一深度的滑动位移
		    		ly[i] = (leijily[i]-lastleiLy[i])*1000+lastLy[i];
		    		zong[i]=(double) Math.sqrt(lx[i]*lx[i]+ly[i]*ly[i]);
		    	}
			}
		}
		//把修正结果插入CorrectDataInfo表中
		List<CorrectDataInfo> allCorrectDataInfos = new ArrayList<CorrectDataInfo>();
		for (int i = 0; i < depthArray.length; i++) {
			CorrectDataInfo correctDataInfo = new CorrectDataInfo();
			correctDataInfo.setDepth(Double.toString(depthArray[i]));
			correctDataInfo.setLx(Double.toString(lx[i]));
			correctDataInfo.setLy(Double.toString(ly[i]));
			correctDataInfo.setError(Double.toString(zong[i]));
			correctDataInfo.setThetaX(Double.toString(leijithetaX[i]));
			correctDataInfo.setThetaY(Double.toString(leijithetaY[i]));
			correctDataInfo.setA0(Double.toString(thetaX0[i]));
			correctDataInfo.setB0(Double.toString(thetaY0[i]));
			correctDataInfo.setA180(Double.toString(thetaX180[i]));
			correctDataInfo.setB180(Double.toString(thetaY180[i]));
			correctDataInfo.setObserverId(obId0);//ob_id和原始测量的A0方向测量的ob_id相同
			allCorrectDataInfos.add(correctDataInfo);
		}
		correctDataInfoDao.insertAll(allCorrectDataInfos);	
		Log.i("info","添加入leijiinfo,obid为"+obId0);
    }
	
	
	/**
	 * 初始化环境
	 */
	private void initMeasureContext() {
		currentMeasureTag = 0;
		depthArray = new double[1];
		thetaXArray=new double[1];
		thetaYArray=new double[1];
		RthetaXArray=new double[1];
		RthetaYArray=new double[1];
		lthetaXArray=new double[1];
		lthetaYArray=new double[1];
		llthetaXArray=new double[1];
		llthetaYArray=new double[1];
		TcorrectArray=new double[1];
		XArray = new double[1];
		YArray = new double[1];
		ZArray = new double[1];
		TArray = new double[1];
		
		initArrays();
		depthX = new double[1];
		lxerrorY = new double[1];
		lyerrorY = new double[1];
	}

	/**
	 * 间距变化监听
	 */
	private OnItemSelectedListener intervalItemSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			// Log.i("info", Integer.toString(depth));
			// 取得当前选择的间距
			initArrays();
			initListView(0);
			saveObserveInfoBtn.setEnabled(true);
		}
		@Override 
		public void onNothingSelected(AdapterView<?> parent) {
		}
	};

	/**
	 * 初始化表中两列数据的数组，根据选择的间距进行初始化
	 */
	private void initArrays() {
		int interval = Integer.parseInt(intervalSpinner.getSelectedItem()
				.toString());

		if ((depth * 100) % interval == 0) {
			length = (int) ((depth * 100) / interval);
		} else {
			length = (int) ((depth * 100) / interval);
			length++;
		}
		// 初始化数组
		depthArray = new double[length];	//长度	
		thetaXArray = new double[length];
		thetaYArray = new double[length];
		RthetaXArray = new double[length];
		RthetaYArray = new double[length];
		lthetaXArray = new double[length];
		lthetaYArray = new double[length];
		llthetaXArray = new double[length];
		llthetaYArray = new double[length];
		TcorrectArray=new double[length];
		thetaArray = new double[length];
		int n_iter = readNum;//读组数-总和
		XArray = new double[n_iter];
		YArray = new double[n_iter];
		ZArray = new double[n_iter];
		TArray = new double[n_iter];
		double depthTemp =(double) depth;
		double intervalTemp = interval;
		// 初始化第一列，深度数据
		for (int i = 0; i < depthArray.length; i++) {
			double j = i;
		//	depthArray[i] =depthTemp - (intervalTemp / 100.0) * i ;//具体的深度数值
			depthArray[i]=new BigDecimal(depthTemp - (intervalTemp / 100.0) * i).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
		}
	}
	 /**
     * 定义一个类，让其继承AsyncTask这个类
     * Params: Void类型，表示传递给异步任务的参数为空
     * Progress: Integer类型，进度条的单位通常都是Integer类型
     * Result：String类型，表示我们获取的数据是否稳定以字符串的形式返回
     *
     */
    public class MyAsyncTask extends AsyncTask<Void, Integer,String>
    {	    
    	//ProgressDialog progressDialog;
    	public MyAsyncTask(){  
    	//	progressDialog= new ProgressDialog(MeasureDataUI.this); //获取测量数据进度对话框
			progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int i) {     
		        dialog.cancel(); 
		        cancel(true);
		        } 
			}); 
    	}
        @Override    
        protected void onPreExecute() {  
        	super.onPreExecute();
       //     progressDialog.show();
        }   
        @SuppressWarnings("finally")
		@Override
       protected String doInBackground(Void... params) {
			if (isCancelled())
				return null;
			String flag = "系统测试不稳定";
			Socket socket = null; /* begin:数据接收实测代码:接收数据、稳定性判断=================== */
	     	InputStream in = null;
			try {
				socket = new Socket(IP, Port);
				in = socket.getInputStream();
				if (isCancelled())
					return null;
				DataInputStream dis = new DataInputStream(in);
				int ecount = 0;// 记录组数
				int n_iter = readNum;//读组数-总和
				int XSum = 0, YSum = 0, ZSum = 0, TSum = 0;
				int step=0;
				while (true) {
					switch(step){
			        case 0:bytefh[0]=dis.readByte();
			        	if(bytefh[0]==(byte) 0xDD)  step=1;break;
			        case 1:bytefh[1]=dis.readByte();
			        	if(bytefh[1]==(byte) 0xDD)  step=2;break;
			        case 2:bytefh[2]=dis.readByte();
			        	if(bytefh[2]==(byte) 0xEE)  step=3;break;
			        case 3:bytefh[3]=dis.readByte();
			        	if(bytefh[3]==(byte) 0xEE)  step=4;break;
			        case 4:
			        	for (int i = 0; i <16; i++) {
			        		bytes[i]=dis.readByte();
						}
			        	ecount++; // 下一组数据
			        	for (int i = 0; i < bytes.length; i++) {
			        		String s=Byte.toString(bytes[i]);//字节转字符串
			        		t[i]= Integer.parseInt(s);//字符串转整形
			        		temp[i]=t[i]&0xff;//16转10进制
						}
			        	if(temp[0]>0)
			        	{
			        		XArray[ecount - 1] =1*Math.pow(-2, 19)+temp[1]*Math.pow(2, 16)+temp[2]*Math.pow(2, 8)+temp[3];
			        	}else {
			        		XArray[ecount - 1] =0*Math.pow(-2, 19)+temp[1]*Math.pow(2, 16)+temp[2]*Math.pow(2, 8)+temp[3];
						}
			        	if(temp[4]>0){
			        		YArray[ecount - 1] = 1*Math.pow(-2, 19)+temp[5]*Math.pow(2, 16)+temp[6]*Math.pow(2, 8)+temp[7];
			        	}else {
			        		YArray[ecount - 1] =0*Math.pow(-2, 19)+temp[5]*Math.pow(2, 16)+temp[6]*Math.pow(2, 8)+temp[7];
						}
						if(temp[8]>0){
							ZArray[ecount - 1] =1*Math.pow(-2, 19)+temp[9]*Math.pow(2, 16)+temp[10]*Math.pow(2, 8)+temp[11];
						}else {
							ZArray[ecount - 1] =0*Math.pow(-2, 19)+temp[9]*Math.pow(2, 16)+temp[10]*Math.pow(2, 8)+temp[11];
						}
						TArray[ecount - 1] =25+(temp[14]*Math.pow(2, 8)+temp[15]-1852)/-9.05;
			            step=0;
			            break;
					}	
					if (ecount == n_iter) {
						// TODO 各组数据处理
						for (int i = 0; i < n_iter; i++) {
							XSum += XArray[i];
							YSum += YArray[i];
							ZSum += ZArray[i];
							TSum += TArray[i];
						}
						double X_ave = (double) (XSum / n_iter); // 求XArray[0:n_iter-1]的平均数
						double Y_ave = (double) (YSum / n_iter);
						double Z_ave = (double) (ZSum / n_iter);
						double T_ave = (double) (TSum / n_iter);
						double sum = 0;
						for (int i = 0; i < XArray.length; i++)
							sum += (XArray[i] - X_ave) * (XArray[i] - X_ave);
						double X_var = sum / XArray.length; // 求XArray[0:n_iter-1]的方差
						sum = 0;
						for (int i = 0; i < YArray.length; i++)
							sum += (YArray[i] - Y_ave) * (YArray[i] - Y_ave);
						double Y_var = sum / YArray.length;
						sum = 0;
						for (int i = 0; i < ZArray.length; i++)
							sum += (ZArray[i] - Z_ave) * (ZArray[i] - Z_ave);
						double Z_var = sum / ZArray.length;
						sum = 0;
						for (int i = 0; i < TArray.length; i++)
							sum += (TArray[i] - T_ave) * (TArray[i] - T_ave);
						double T_var = sum / TArray.length;
						sum = 0;
						if (X_var > variance || Y_var > variance || Z_var > variance || T_var > variance) // 数据不稳定，直接结束程序，或者重新测量，as
						{
							flag = "系统测试不稳定";
						} else {
							flag = "系统测试稳定";
						}
						break;
					}
				}
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showMsg(e.getLocalizedMessage());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				showMsg(e.getLocalizedMessage());
			} finally {
				try {
					if (in != null) {
						in.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				try {
					if (socket != null)
						socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return flag;
			}
			/* end:数据接收实测代码=================== */
			/*begin:实验室（模拟数据）测试代码：==============*/
//				flag = "系统测试稳定";
//			  return flag;
			/* end:实验室（模拟数据）测试代码=================== */
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			Log.i("info","onProgressUpdate()");
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// 更新我们的systemTestView控件
			systemTestView.setText(result);
			// 使ProgressDialog框消失
			progressDialog.dismiss();
			if ("系统测试稳定".equals(systemTestView.getText())) {
				if(ifSecond){
				    double results[] = new double[8];// 八组数据
				    /*begin:实验室（模拟数据）测试代码：==============*/
				/*	XArray = new double[] {21385,21385,21385,21448,21448,21448,21414,21414};
					YArray = new double[] {255484,255484,255484,255496,255496,255496,255485,255485};
					ZArray = new double[] {-4677,-4677,-4677,-4575,-4575,-4575,-4640,-4640};
				-15	TArray = new double[] {(double) 27.0994,(double) 27.0994,(double) 26.989,(double) 27.0994,(double) 26.989,(double) 27.0994,(double) 26.989,(double) 26.989};	
				/*	XArray = new double[] {55422,55422,55422,55407,55407,55407,55444,55444};
				    YArray = new double[] {247621,247621,247621,247607,247607,247607,247601,247601};
					ZArray = new double[] {-6201,-6201,-6201,-6263,-6263,-6263,-6249,-6249};
			     -1   TArray = new double[] {(double) 27.0994,(double) 26.989,(double) 26.989,(double) 27.0994,(double) 27.0994,(double) 26.989,(double) 26.989,(double) 27.0994};*/
//					XArray = new double[] {3560,3560,3541,3541,3541,3532,3532,3532};
//					YArray = new double[] {256429,256429,256439,256439,256439,256440,256440,256440};
//					ZArray = new double[] {-3950,-3950,-3922,-3922,-3922,-3928,-3928,-3928};
//					TArray = new double[] {(double) 27.2099,(double) 27.2099,(double) 27.2099,(double) 27.3204,(double) 27.2099,(double) 27.0994,(double) 27.0994,(double) 27.0994};
//					for (int i = 0; i < XArray.length; i++) {
//					XArray[i] += w;// 改变数据的值
//					YArray[i] += w;
//					ZArray[i] += w;
//					TArray[i] +=0.5;
//				    }
//				    w = w + 1;
				    /*end:实验室（模拟数据）测试代码==============*/
			    	double[] ave = new double[4];
				    ave = MeanMethod.getArithmeticMean(XArray, YArray, ZArray, TArray);
				    int interval = Integer.parseInt(intervalSpinner.getSelectedItem().toString());
				    // 调用inclinometer中的方法，返回thetaX,thetaZ
				    results = InclinometerControl.getMeasureResult2(ave[0], ave[1], ave[2], ave[3], interval,qjSpinner.getSelectedItem().toString());
				    thetaXArray[currentMeasureTag]=results[0];//单位：弧度
				    thetaYArray[currentMeasureTag]=results[1];//单位：弧度
				    thetaArray[currentMeasureTag]=results[2];//倾角
				    TcorrectArray[currentMeasureTag]=results[3];//温度
				    Log.i("qj", "qj:"+qjSpinner.getSelectedItem().toString());
				    Log.i("xyzt", "Q:"+results[2]+",AQ:"+results[0]+",BQ:"+results[1]+",T:"+results[3]);
				    temperatureTextView.setText(Common.remainTwoNum(results[3])+"");//显示温度
				    thetaView.setText(Common.remainFourNum((double) (results[2]*180/3.1415926))+"");//显示倾角,单位为度	
				    sureBtn.setEnabled(true);
					sureBtn.setBackgroundColor(lightGreen);
				}
			}else if ("系统测试不稳定".equals(systemTestView.getText())) {
				showMsg("系统测试不稳定，请重新测量！");//表示当前深度点数据方差过大
			}
        }
    }   
	/*** 测量按钮监听*/
	private OnClickListener measureBtnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			ifSecond=true;
			//获取IP，Port
			SharedPreferences sharedPreferences=ContextApplication.getAppContext().getSharedPreferences("configuration",0);
	    	IP=sharedPreferences.getString("Ip",null);
	    	Port=Integer.parseInt(sharedPreferences.getString("Port",null));
	    	second=Double.parseDouble(second_edit.getText().toString().trim());
	    	//new MyAsyncTask().execute();// 在UI Thread当中实例化AsyncTask对象，并调用execute方法
	    	int time=(int)(second*1000);
	    	long time1=time;
	    	callAsynchronousTask(time1);
	    	
	    	
       }		
    };  
    public void callAsynchronousTask(long time) {
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {       
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {       
                        try {
                        	if(ifSecond){
                        		Log.i("ifs", "ifSecond:"+ifSecond);
                        	task = new MyAsyncTask();
                        	task.execute();
                        	}
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        if(ifSecond==false){
        	timer.cancel();
        }
        timer.schedule(doAsynchronousTask, 0, time); //execute in every 50000 ms
        
    }
     /*** 确定按钮监听*/
    private OnClickListener sureBtnClickListener = new OnClickListener() {
	    @Override
	    public void onClick(View v) {
	    	ifSecond=false;
	    	task.cancel(true);
	    	Log.i("ifs", "ifsecond:"+ifSecond);
	    	showMsg("数据稳定");
	    	int interval = Integer.parseInt(intervalSpinner.getSelectedItem().toString());
	    	//判断一下当前obId是A0方向的，还是A180方向的（当前obId是第二次测量的）
			if(meaAngleNO1.equals(MEASURE_ANGLE_0)){
				RthetaXArray[currentMeasureTag]=thetaXArray[currentMeasureTag];
            	RthetaYArray[currentMeasureTag]=thetaYArray[currentMeasureTag];	
			}else{//如果是180方向，则用（A0-A180）/2
				int ob_id_0;
				Log.i("info", "meaAngleNO1:"+meaAngleNO1+",baseId:"+baseId+",observecount:"+observecount);
				ObserveInfo observeInfo0=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseId,observecount);
    			ob_id_0=observeInfo0.getObserveId();//A180方向的ob_id
    			List<DataInfo> DataInfoList0=dataInfoDao.selectDataInfos(ob_id_0);//存放A0方向测量结果
    			int n=DataInfoList0.size();//获得数据的长度
        		double[] RthetaX_0 = new double[n];
        		double[] RthetaY_0 = new double[n];
        		//获得测量的数据，四个角度数组
        		for(int i=0;i<n;i++){
        			DataInfo item0=DataInfoList0.get(i);
        			RthetaX_0[i]=Double.parseDouble(item0.getThetaX());//单位：弧度
        			RthetaY_0[i]=Double.parseDouble(item0.getThetaY());
        		}
        		RthetaXArray[currentMeasureTag]=(RthetaX_0[currentMeasureTag]-thetaXArray[currentMeasureTag])/2;
            	RthetaYArray[currentMeasureTag]=(RthetaY_0[currentMeasureTag]-thetaYArray[currentMeasureTag])/2; 
			}
        	if(currentMeasureTag==0){
        		lthetaXArray[currentMeasureTag]=Math.sin(RthetaXArray[currentMeasureTag])*interval*0.01;
        		lthetaYArray[currentMeasureTag]=Math.sin(RthetaYArray[currentMeasureTag])*interval*0.01;
        	}else{
        		lthetaXArray[currentMeasureTag]=Math.sin(RthetaXArray[currentMeasureTag])*interval*0.01+lthetaXArray[currentMeasureTag-1];
        		lthetaYArray[currentMeasureTag]=Math.sin(RthetaYArray[currentMeasureTag])*interval*0.01+lthetaYArray[currentMeasureTag-1];
        	}
        	if(observecount==1){//第一次观测
        		llthetaXArray[currentMeasureTag]=lthetaXArray[currentMeasureTag]*1000;
        		llthetaYArray[currentMeasureTag]=lthetaYArray[currentMeasureTag]*1000;;
    		}else if(observecount==2){
    			int ob_id;
    			//判断一下当前obId是A0方向的，还是A180方向的（当前obId是第二次测量的）
    			if(meaAngleNO1.equals(MEASURE_ANGLE_0)){
    				ObserveInfo observeInfo0=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseId,observecount-1);
        			ob_id=observeInfo0.getObserveId();//A0方向的ob_id
    			}else{
    				ObserveInfo observeInfo0=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_180,baseId,observecount-1);
        			ob_id=observeInfo0.getObserveId();//A180方向的ob_id
    			}      			
    			List<RealInfo> RealInfoList=realInfoDao.selectRealInfos(ob_id,Integer.toString(currentMeasureTag));//存放A0方向测量结果
    			int n2=RealInfoList.size();//获得数据的长度
    			double[] lastLx = new double[n2];
    			double[] lastLy = new double[n2];
    			//获得测量的数据，四个角度数组
    			for(int i=0;i<n2;i++){
    				RealInfo item=RealInfoList.get(i);
    				lastLx[i]=Double.parseDouble(item.getLtheta_A());//单位：cm
    				lastLy[i]=Double.parseDouble(item.getLtheta_B());
    			}
    			llthetaXArray[currentMeasureTag]=(lthetaXArray[currentMeasureTag]-lastLx[0])*1000;
        		llthetaYArray[currentMeasureTag]=(lthetaYArray[currentMeasureTag]-lastLy[0])*1000;
    		} else {
    			int ob_id;
    			//判断一下当前obId是A0方向的，还是A180方向的（当前obId是第二次测量的）
    			if(meaAngleNO1.equals(MEASURE_ANGLE_0)){
    				ObserveInfo observeInfo0=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_0,baseId,observecount-1);
        			ob_id=observeInfo0.getObserveId();//A0方向的ob_id
    			}else{
    				ObserveInfo observeInfo0=observeInfoDao.selectObserveInfo(MEASURE_ANGLE_180,baseId,observecount-1);
        			ob_id=observeInfo0.getObserveId();//A180方向的ob_id
    			}      			
    			List<RealInfo> RealInfoList=realInfoDao.selectRealInfos(ob_id,Integer.toString(currentMeasureTag));//存放A0方向测量结果
    			int n2=RealInfoList.size();//获得数据的长度
    			double[] lastLx = new double[n2];
    			double[] lastLy = new double[n2];
    			double[] lastLlx = new double[n2];
    			double[] lastLly = new double[n2];
    			//获得测量的数据，四个角度数组
    			for(int i=0;i<n2;i++){
    				RealInfo item=RealInfoList.get(i);
    				lastLx[i]=Double.parseDouble(item.getLtheta_A());//单位：cm
    				lastLy[i]=Double.parseDouble(item.getLtheta_B());
    				lastLlx[i]=Double.parseDouble(item.getLltheta_A());//单位：cm
    				lastLly[i]=Double.parseDouble(item.getLltheta_B());
    			}
    			/**/
    			llthetaXArray[currentMeasureTag]=(lthetaXArray[currentMeasureTag]-lastLx[0])*1000+lastLlx[0];
        		llthetaYArray[currentMeasureTag]=(lthetaYArray[currentMeasureTag]-lastLy[0])*1000+lastLly[0];
    		}
        	
        	RealInfo realInfo = new RealInfo();
        	realInfo.setTheta_A(Double.toString(RthetaXArray[currentMeasureTag]));
        	realInfo.setTheta_B(Double.toString(RthetaYArray[currentMeasureTag]));
        	realInfo.setLtheta_A(Double.toString(lthetaXArray[currentMeasureTag]));
        	realInfo.setLtheta_B(Double.toString(lthetaYArray[currentMeasureTag]));
        	realInfo.setLltheta_A(Double.toString(llthetaXArray[currentMeasureTag]));
        	realInfo.setLltheta_B(Double.toString(llthetaYArray[currentMeasureTag]));
        	realInfo.setCurrentMeasureTag(Integer.toString(currentMeasureTag));
        	realInfo.setObserverId(obId);
        	// 执行插入操作
			int _obId1=0;
			_obId1= realInfoDao.add(realInfo);
			if(_obId1==0){
			}else{
				Log.i("info","插入成功");
			}
        	 depthX = new double[currentMeasureTag + 1];
			    lxerrorY = new double[currentMeasureTag + 1];
			    lyerrorY = new double[currentMeasureTag + 1];
			    for (int i = 0; i <= currentMeasureTag; i++) {
			    	depthX[i] = (double) depthArray[i];
			    	lxerrorY[i] = (double)(llthetaXArray[i]);//图显示的时候，减去第一次有效测量的结果
			    	lyerrorY[i] = (double)(llthetaYArray[i]);
			    }
        	 // 更新图表
		    chatLoc.removeAllViews();
		    initMeasureView(depth, depthX, lxerrorY,lyerrorY);
        	// 更新表格
		    initListView(0);
		    currentMeasureTag++; // 指针指向下一个
        	/*** 系统稳定，测试成功后，发出 提示音**/
		    sp.play(music, 1, 1, 0, 0, 1);
		    sureBtn.setEnabled(false);
			sureBtn.setBackgroundColor(lightRed);
		    if (currentMeasureTag == length) { // 此时已经测到距离地面最近的一个点了，不需要再测了
				showMsg("测量结束，请点击保存按钮进行保存！");
				measureBtn.setEnabled(false);
				measureBtn.setBackgroundColor(lightRed);
				saveMeasureInfoBtn.setEnabled(true);
				saveMeasureInfoBtn.setBackgroundColor(lightGreen);
			 }	
		  		
         }		
    };
	/*** 返回按钮监听*/
	private OnClickListener backOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (currentMeasureTag == length) { // 此时已经测到距离地面最近的一个点了，不需要再测了
				measureBtn.setEnabled(true);
				measureBtn.setBackgroundColor(lightGreen);
			}
			if (currentMeasureTag > 1) {
				currentMeasureTag--;
            	temperatureTextView.setText(Common.remainTwoNum(TcorrectArray[currentMeasureTag])+"");
            	thetaView.setText(Common.remainFourNum(thetaArray[currentMeasureTag]*180/3.1415926)+"");
            	thetaXArray[currentMeasureTag]=0;
				thetaYArray[currentMeasureTag]=0;
				TcorrectArray[currentMeasureTag]=0;
				llthetaXArray[currentMeasureTag]=0;
				llthetaYArray[currentMeasureTag]=0;
				depthX = new double[currentMeasureTag];
				lxerrorY = new double[currentMeasureTag];
				lyerrorY = new double[currentMeasureTag];
				for (int i = 0; i < currentMeasureTag; i++){
					depthX[i] = (double) depthArray[i];
					lxerrorY[i] = (double) (llthetaXArray[i]);
					lyerrorY[i] = (double) (llthetaYArray[i]);
				}
            	// 更新表格
				int isBack=1;
				initListView(isBack);
				// 更新图表
				chatLoc.removeAllViews();
				initMeasureView(depth, depthX,lxerrorY,llthetaYArray);
			} else if (currentMeasureTag == 1) {
				currentMeasureTag--;
				thetaXArray[currentMeasureTag]=0;
				thetaYArray[currentMeasureTag]=0;
				TcorrectArray[currentMeasureTag]=0;
				llthetaXArray[currentMeasureTag]=0;
				llthetaYArray[currentMeasureTag]=0;
            	temperatureTextView.setText(Common.remainTwoNum(TcorrectArray[currentMeasureTag])+"");
            	thetaView.setText(Common.remainFourNum(thetaArray[currentMeasureTag]*180/3.1415926)+"");
            	depthX = new double[1];
				lxerrorY = new double[1];
				lyerrorY = new double[1];
				// 更新图表
				chatLoc.removeAllViews();
				initMeasureView(depth, depthX,lxerrorY,lyerrorY);
            	// 更新表格
				int isBack=1;
				initListView(isBack);
			}
			saveMeasureInfoBtn.setEnabled(false);
			saveMeasureInfoBtn.setBackgroundColor(lightRed);
		}
	};
	private void showMsg(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}
	private OnItemSelectedListener measureangleItemSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			saveObserveInfoBtn.setEnabled(true);
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	};	
	private OnItemSelectedListener qjItemSelectedListener = new OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			saveObserveInfoBtn.setEnabled(true);
		}
		@Override
		public void onNothingSelected(AdapterView<?> parent) {
		}
	};
	/*** 用来获取输入的数据，保存观测参数*/
	private OnClickListener saveObserveInfoListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
		
			ObserveInfo observeInfo = new ObserveInfo();
			String observer = observerEdit.getText().toString().trim();
			String time = date_edit.getText().toString().trim();
			String interval = intervalSpinner.getSelectedItem().toString();
			String measureangle = measureangleSpinner.getSelectedItem().toString();// 当前进行测量的方向是这个		
			String qj = qjSpinner.getSelectedItem().toString();
			observeInfo.setObserver(observer);
			observeInfo.setTime(time);
			observeInfo.setInterval(interval);
			observeInfo.setMeasurecount(measureangle);
			observeInfo.setBaseId(baseId);
			if (BaseUtil.isEmpty(observeInfo, r_MeasureDataUI.this)) {
				// meaCount == 1表示进入测量页面选择的一个测量方向，具体是哪个方向并不知道，因为只要设置第二次测量的方向不等于第一次测量的方向就行
				if (meaCount == 1) {
					
					// count的值需要判断是从哪个界面进来的，如果是从新项目进来的，count=1
					if ("new".equals(from)) {
						observeInfo.setCount(1);
						observecount=1;
					}
					// 如果是从老项目进来的，则需要先判断之前的count是几，然后+1
					if ("old".equals(from)) {
						/***判断上次的count为第几次，然后加1**/
						List<ObserveInfo> alls = new ArrayList<ObserveInfo>();
						alls = observeInfoDao.selectObserverInfos(baseId,
								measureangle);
						// 判断取出的记录是否为空
						if (alls.size() < 1) {                                 
							observeInfo.setCount(1);
						} else {
							int max = 1;
							for (ObserveInfo observeInfo2 : alls) {
								int j = observeInfo2.getCount();
								if (j > max) {
									max = j;
								}
							}
							max++;
							observecount=max;
							observeInfo.setCount(max);	
						}
					}
					// 执行插入操作
					int _obId = observeInfoDao.insert(observeInfo);
					if (MEASURE_ANGLE_0.equals(measureangle)) {
						observeInfo.setMeasurecount(MEASURE_ANGLE_180);
					} else if (MEASURE_ANGLE_180.equals(measureangle)) {
						observeInfo.setMeasurecount(MEASURE_ANGLE_0);
					}
					_obId2 = observeInfoDao.insert(observeInfo);
					if (_obId > 0 && _obId2 > 0) {// 表示插入成功
						Toast.makeText(r_MeasureDataUI.this, "保存参数成功！",
								Toast.LENGTH_SHORT).show();
						int lastCount=observeInfoDao.getLastCountByBaseId(baseId);//上一次测量的测试cishu
						String lcount=String.valueOf(lastCount);//此时的lastCount就是本次的count
						measurecountTextView.setText(lastCount+"");//在页面显示此时的观测次数	
						saveObserveInfoBtn.setEnabled(false);//保存参数按钮不可用
						observerEdit.setEnabled(false);//监测人员编辑框不可用
						date_edit.setEnabled(false);//时间编辑不可用
						intervalSpinner.setEnabled(false);//监测间距不可选择
						measureangleSpinner.setEnabled(false);//测试方向不可选择
						qjSpinner.setEnabled(false);	
						measureBtn.setEnabled(true);
						measureBtn.setBackgroundColor(lightGreen);
						backBtn.setEnabled(true);
						backBtn.setBackgroundColor(lightGreen);
						
						// 保存成功，在右下角显示监测对象的基本信息
						intervalTextView.setText(interval);
						measureangleTextView.setText(measureangle);
						meaAngleNO1=measureangle;//用来记录第一次测量的测试方向（正反两次观测为一次完整观测）
						obId = _obId; // 赋值
					} else {
						showMsg("保存参数失败！"); // 此处需要进行相关的处理操作********如果有一个插入失败，那么将进行回退操作*************************************************
					}
				} else if (meaCount == 2) {
					// 此处的保存按钮，是用来更新数据库中ob_id=obId2的观测数据信息，因为为了保证数据的一致性，在第一次保存的时候就自动生成了第二次的记录
					
					if(measureangle.equals(meaAngleNO1)){//meaAngleNO1表示第一次的测量方向（正反两次观测为一次完整观测）
						showMsg("保存参数失败，请变换测试方向！");//第二次测量方向不能和第一次测量方向相同
					}else{
						observeInfo.setObserveId(_obId2);
						observeInfo.setCount(observecount);
						Boolean flag = observeInfoDao.update(observeInfo);
						measureangleTextView.setText(measureangle);
						meaAngleNO1=measureangle;
						if (flag == true) {
							Toast.makeText(r_MeasureDataUI.this, "保存参数成功！",
									Toast.LENGTH_SHORT).show();
							saveObserveInfoBtn.setEnabled(false);
							measureangleSpinner.setEnabled(false);
							measureBtn.setEnabled(true);
							measureBtn.setBackgroundColor(lightGreen);
							backBtn.setEnabled(true);
							backBtn.setBackgroundColor(lightGreen);
							
						} else {
							showMsg("保存参数失败！");
						}
						obId = _obId2;
					}
				}
			}
			// Log.i("info", "观测记录，插入的ID为："+_obId);
		}
	};
	/**
	 * 监听返回键，公共部分
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			sureDialog();
			return true;
		}
		return true;
	}

	/**
	 * 退出程序，确认框，公共部分
	 */
	public void sureDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定退出程序吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// AccoutList.this.finish();
						// System.exit(1);
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}
	

	protected XYMultipleSeriesDataset buildDataset(String[] titles,
			List<double[]> xValues, List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

		int length = titles.length; // 有几条线
		for (int i = 0; i < length; i++) {
			XYSeries series = new XYSeries(titles[i]); // 根据每条线的名称创建
			double[] xV = (double[]) xValues.get(i); // 获取第i条线的数据
			double[] yV = (double[]) yValues.get(i);
			int seriesLength = xV.length; // 有几个点

			for (int k = 0; k < seriesLength; k++) // 每条线里有几个点
			{
				series.add(xV[k], yV[k]);
			}

			dataset.addSeries(series);
		}

		return dataset;
	}

	/**
	 * 返回渲染器
	 * 
	 * @param colors
	 * @param styles
	 * @param fill
	 * @return
	 */
	protected XYMultipleSeriesRenderer buildRenderer(int[] colors,
			PointStyle[] styles, boolean fill) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			r.setFillPoints(fill);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	/**
	 * 设置图表的属性
	 * 
	 * @param renderer
	 * @param title
	 * @param xTitle
	 * @param yTitle
	 * @param xMin
	 * @param xMax
	 * @param yMin
	 * @param yMax
	 * @param axesColor
	 * @param labelsColor
	 */
	protected void setChartSettings(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setAxesColor(axesColor);
		// renderer.setZoomButtonsVisible(true); //设置放大缩小按钮
		// 标题颜色
		renderer.setLabelsColor(labelsColor);
		// 设置刻度的颜色
		renderer.setXLabelsColor(Color.BLUE);
		renderer.setYLabelsColor(0, Color.BLUE);
		// 设置图标内部颜色
		renderer.setApplyBackgroundColor(true);
		// renderer.setBackgroundColor(Color.WHITE);
		// 设置图标外部颜色
		renderer.setMarginsColor(Color.LTGRAY);
		renderer.setShowLegend(true); // 显示图例
	}

	/**
	 * 监听点击时间edit的方法，然后弹出时间选择器
	 */
//	public boolean onTouch(View v, MotionEvent event) {
//		if (event.getAction() == MotionEvent.ACTION_DOWN) {
//
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			View view = View.inflate(this, R.layout.date_time_dialog, null);
//			final DatePicker datePicker = (DatePicker) view
//					.findViewById(R.id.date_picker);
//		    final TimePicker timePicker = (android.widget.TimePicker) view
//		    		.findViewById(R.id.time_picker);
//
//			builder.setView(view);
//
//			Calendar cal = Calendar.getInstance();
//			cal.setTimeInMillis(System.currentTimeMillis());
//			datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
//					cal.get(Calendar.DAY_OF_MONTH), null);
//
//		    timePicker.setIs24HourView(true);
//			timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
//			timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
//
//			final int inType = date_edit.getInputType();
//			date_edit.setInputType(InputType.TYPE_NULL);
//			date_edit.onTouchEvent(event);
//			date_edit.setInputType(inType);
//			date_edit.setSelection(date_edit.getText().length());
//
//			//builder.setTitle("选取时间");
//			builder.setPositiveButton("确  定",
//					new DialogInterface.OnClickListener() {
//						@Override
//						public void onClick(DialogInterface dialog, int which) {
//
//							StringBuffer sb = new StringBuffer();
//							sb.append(String.format("%d-%02d-%02d",
//									datePicker.getYear(),
//									datePicker.getMonth() + 1,
//									datePicker.getDayOfMonth()));
//							sb.append(" ");
//							sb.append(timePicker.getCurrentHour()).append(":")
//							  .append(timePicker.getCurrentMinute());
//							date_edit.setText(sb);
//							dialog.cancel();
//						}
//					});
//			Dialog dialog = builder.create();
//			dialog.show();
//		}
//		return true;
//	}
	
	/**
	 * 点击空白处时，隐藏键盘
	 * 
	 *
	 */
//	@Override
//    public boolean onTouchEvent(MotionEvent event){
//        if(event.getAction()==MotionEvent.ACTION_DOWN){
//            if(r_MeasureDataUI.this.getCurrentFocus() != null && r_MeasureDataUI.this.getCurrentFocus().getWindowToken() != null){
//                    inputMethodManager.hideSoftInputFromWindow(r_MeasureDataUI.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
//            }
//        }
//        return super.onTouchEvent(event);
//    }
	
	
}

